package com.scse.bms.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.scse.bms.domain.UserVO;
import com.scse.bms.mapper.UserMapper;
import com.scse.bms.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


/**
 * @Title: AdminServiceImpl
 * @Author: 吴赠禹
 * @Date: 2021/1/7 10:40
 * @Version: 1.0
 * @Description: 管理员Service层
 */

@Slf4j
@Service("adminService")
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 管理员修改用户密码
     *
     * @param map
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserPass(Map<String, String> map) {
        if (map.get("id") == null || map.get("password") == null) {
            log.warn(log.getClass().getSimpleName() + " [updateUserPass] 非法请求！");
            return -1;
        }
        // 使用md5加密
        map.put("password", SecureUtil.md5(map.get("password")));
        int res = userMapper.updatePassword(map);
        log.info("管理员修改用户密码，目标ID：" + map.get("id"));
        return res;
    }

    /**
     * 管理员修改用户状态
     *
     * @param map
     * @return 受影响行数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserValid(Map<String, Integer> map) {
        if (map.get("id") == null || map.get("valid") == null) {
            log.warn(log.getClass().getSimpleName() + " [updateUserValid] 非法请求！");
            return -1;
        }
        // 参数顺序：valid、id
        int res = userMapper.updateUserValid(map.get("valid"), map.get("id"));
        return res;
    }

    /**
     * 管理员登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserVO selectAdminUser(String username, String password) {
        final String ADMIN = "管理员";
        String encrypt = DigestUtil.md5Hex(password);
        UserVO user = userRoleMapper.selectOneByUsernameAndPasswordUserVo(username, encrypt);
        if (ObjectUtil.isNotNull(user) && ADMIN.equals(user.getRole())) {
            return user;
        }
        return null;
    }
}
